import yargs from 'yargs';
import fs from 'fs';
import path from 'path';
import { dataGet } from '#Utils/helper.js';

const temp = (name) => {
    return `
import { Controller } from "#Controller/controller.js";

class ${name} extends Controller {
    index = async (ctx) => {
        this.success(ctx, "创建成功");
    }
}

export default new ${name}();

`
}

const baseTemp = () => {
    return `
export class Controller {

    toJson(ctx, code = 200, data = '', msg = '', isOk = true) {
        ctx.status = code;
        ctx.type = 'json';
        ctx.body = {
            data,
            code,
            msg,
            isOk
        };

    }

    success(ctx, data, msg = 'success') {
        this.toJson(ctx, 200, data, msg, true);
    }

    error(ctx, code = 500, msg = 'error') {
        this.toJson(ctx, code, '', msg, false);
    }
}
`;
}


const indexTemp = () => {
    return `
import {controller} from '{controllerPath}';


export {
    {controller},
}`
}

function createController() {

    const argv = yargs(process.argv.slice(2)).argv, name = dataGet(argv, 'name');

    console.log('创建控制器');
    console.log('控制器名称：', name);


    if (!name) {
        console.log('请输入控制器名称');
        return;
    }
    const importBase = '#Controllers',
        indexPath = path.join(rootDir(), 'index.js'),
        basePath = path.join(rootDir(), 'controller.js'),
        tartgetPath = path.join(rootDir(), `${name}.js`),
        targetDir = path.dirname(tartgetPath);

    try {


        // 创建控制器文件
        if (fs.existsSync(path.resolve(rootDir(), `${name}.js`))) {
            log(`控制器 ${name} 已经存在`);
            return
        }

        if (!fs.existsSync(basePath)) {
            fs.writeFileSync(basePath, baseTemp());
        }

        if (!fs.existsSync(targetDir)) {
            console.log(`创建控制器目录 ${targetDir}`);

            fs.mkdirSync(targetDir, { recursive: true, mode: '0755' });
        }


        fs.writeFileSync(path.resolve(rootDir(), `${name}.js`), temp(ucwords(name)));


        if (!fs.existsSync(indexPath)) {
            let indexContent = indexTemp().replaceAll('{controller}', ucwords(name)).replaceAll('{controllerPath}', `${importBase}/${name}.js`);
            fs.writeFileSync(indexPath, indexContent.trimStart(), 'utf8');
            console.log(`新增了 index.js, 在 index.js 中添加了 ${name} 的导出`);
            return
        }

        // 更新 index.js 文件，增加控制器的导出
        let indexContent = fs.readFileSync(indexPath, 'utf8');

        let importTemp = `import ${ucwords(name)} from "${importBase}/${name}.js";`,
            exportTemp = `    ${ucwords(name)}`;

        // 如果该控制器没有导出，则添加它
        if (!indexContent.includes(importTemp)) {
            indexContent = indexContent.replace('\n\nexport {', importTemp + '\n\n\nexport {');
            indexContent = indexContent.replace('}', exportTemp + ',\n}');
            fs.writeFileSync(indexPath, indexContent, 'utf8');
            console.log(`在 index.js 中添加了 ${name} 的导出`);
        }

        console.log(indexContent);

    } catch (error) {
        console.log('控制器创建失败', error);

    }


    console.log('创建成功');
}

const ucwords = (str) => {
    let name = path.basename(str);
    return name.charAt(0).toUpperCase() + name.slice(1);
}

const rootDir = () => {
    return path.join(import.meta.dirname, '../../', 'app', 'http', 'controllers')
}
const argv = yargs(process.argv.slice(2)), name = dataGet(argv, 'name');

createController();
